package com.example.jucsample.cdl;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

public class HttpCall {

    public static void main(String[] args) throws Exception {

//        useFuture();
        useCdl();

    }

    public static void useFuture() throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future<String>> results = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            final int n = i;
            Future<String> future = executorService.submit(() -> {
                Random random = new Random();
                Thread.sleep(random.nextInt(5) * 1000 + 1500);
                return n + " is ok";
            });
            results.add(future);
        }
        for (Future<String> result : results) {
//            System.out.println(result.get());
            //等待时间不止3秒，可能第一个等了2秒，第二个又等了1秒，第三个等了1秒
            System.out.println(result.get(3L, TimeUnit.SECONDS));
        }
    }

    public static void useCdl() throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future<String>> results = new ArrayList<>();
        CountDownLatch cdl = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            final int n = i;
            Future<String> future = executorService.submit(() -> {
                try {
                    Random random = new Random();
                    Thread.sleep(random.nextInt(5) * 1000 + 1500);
                    return n + " is ok";
                } finally {
                    cdl.countDown();
                }
            });
            results.add(future);
        }
        cdl.await(2L, TimeUnit.SECONDS);
        for (Future<String> result : results) {
//            System.out.println(result.get());
            if (result.isDone()) {
                try {
                    System.out.println(result.get());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
